package com.jams.goodox.update;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.utils.Utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by jams on 2016/10/27.
 * ***
 * Tel: ***
 */

class UpDateDialog {

    //更新对话框
    static Dialog UpdateDialog(final Context context, final String version, String content, final boolean forceUpDate, final UpDateActionListener upDateActionListener) {
        final Dialog dialog = new Dialog(context, R.style.DialogStyle);
        dialog.setCancelable(false);
        View view = LayoutInflater.from(context).inflate(R.layout.up_date, null);
        dialog.setContentView(view);
        TextView tvVersion = (TextView) view.findViewById(R.id.tv_update_version);
        TextView tvContent = (TextView) view.findViewById(R.id.tv_up_date_content);
        TextView tvCancel = (TextView) view.findViewById(R.id.tv_up_date_cancel);
        TextView tvConfirm = (TextView) view.findViewById(R.id.tv_up_date_confirm);
        final LinearLayout lvBtnGroup = (LinearLayout) view.findViewById(R.id.lv_btn_group);
        final LinearLayout progressGroup = (LinearLayout) view.findViewById(R.id.update_progress_group);
        final ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.update_pb);
        if (forceUpDate) {
            tvCancel.setVisibility(View.GONE);
        } else {
            tvCancel.setVisibility(View.VISIBLE);
        }
        tvVersion.setText("V" + version);
        tvContent.setMovementMethod(new ScrollingMovementMethod());
        tvContent.setText(content);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                upDateActionListener.cancel();
                SePref.putUpDateTime();//保存当前时间
            }
        });
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (forceUpDate) {
                    //强制更新
                    lvBtnGroup.setVisibility(View.GONE);
                    progressGroup.setVisibility(View.VISIBLE);
                    downloadApk(context, progressBar, lvBtnGroup, progressGroup, dialog);
                } else {
                    //不是强制更新就回调
                    dialog.cancel();
                    upDateActionListener.confirm();
                }
            }
        });
        Window mWindow = dialog.getWindow();
        mWindow.setWindowAnimations(R.style.UpDataDialogStyle);
        WindowManager.LayoutParams lp = mWindow.getAttributes();
        lp.width = Utils.dp2px(context, 250);
        mWindow.setAttributes(lp);
        dialog.show();
        return dialog;
    }

    //有最新apk,提示安装
    static Dialog UpdateHasApkDialog(Context context, String version, final UpDateHasApkActionListener upDateActionListener) {
        final Dialog dialog = new Dialog(context, R.style.DialogStyle);
        dialog.setCancelable(false);
        View view = LayoutInflater.from(context).inflate(R.layout.up_date_has_apk, null);
        dialog.setContentView(view);
        TextView tvVersion = (TextView) view.findViewById(R.id.tv_update_version);
        TextView tvConfirm = (TextView) view.findViewById(R.id.tv_up_date_has_apk_confirm);
        tvVersion.setText("V"+version);
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                upDateActionListener.confirm();
                File apkFile = new File(UpDateVersionUtils.ApkPath);
                if (!apkFile.exists()) {
                    dialog.dismiss();
                }
            }
        });
        Window mWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = mWindow.getAttributes();
        lp.width = Utils.dp2px(context, 250);
        mWindow.setAttributes(lp);
        dialog.show();
        return dialog;
    }

    private static void downloadApk(final Context context, final ProgressBar progressBar, final LinearLayout lvBtnGroup, final LinearLayout progressGroup, final Dialog dialog) {
        new Thread(new Runnable() {
            public void run() {
                InputStream inputStream = null;
                FileOutputStream outputStream = null;
                try {
                    int size;
                    URL url = new URL(UpDateVersionUtils.Apk_Update_Url);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    size = connection.getContentLength();
                    progressBar.setMax(size);
                    inputStream = connection.getInputStream();
                    outputStream = new FileOutputStream(UpDateVersionUtils.ApkPath);
                    BufferedInputStream bis = new BufferedInputStream(inputStream);
                    byte[] buffer = new byte[1024];
                    int len;
                    int total = 0;
                    while ((len = bis.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, len);
                        total += len;
                        progressBar.setProgress(total);
                        if (total == size) {
                            UpDateVersionUtils.installApk(context);
                            dialog.dismiss();
                        }
                    }
                    inputStream.close();
                    outputStream.close();
                } catch (Exception e) {
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showLong(context, "更新失败请重试");
                            lvBtnGroup.setVisibility(View.VISIBLE);
                            progressGroup.setVisibility(View.GONE);
                            progressBar.setProgress(0);
                        }
                    });
                }finally {
                    try {
                        if(outputStream != null)outputStream.close();
                        if(inputStream != null) inputStream.close();
                    }catch (IOException e){

                    }

                }
            }
        }).start();
    }

    public interface UpDateActionListener {
        void cancel();

        void confirm();
    }

    public interface UpDateHasApkActionListener {
        void confirm();
    }
}
